import 'dart:convert';
import '../entity/content_submission.dart';
import '../entity/user.dart';
import '../utils/local_store.dart';

/// 内容分享数据仓库
class ContentRepository {
  static final ContentRepository _instance = ContentRepository._internal();
  
  factory ContentRepository() {
    return _instance;
  }
  
  ContentRepository._internal();

  final LocalStore _localStore = LocalStore();

  /// 存储键常量
  static const String _submissionsKey = 'content_submissions';
  static const String _challengeTasksKey = 'challenge_tasks';

  /// 获取所有内容分享
  Future<List<ContentSubmission>> getAllSubmissions() async {
    try {
      final String submissionsJson = _localStore.getTextValue(
        _submissionsKey,
        defaultValue: '[]',
      );
      
      final List<dynamic> jsonList = jsonDecode(submissionsJson);
      return jsonList.map((json) => ContentSubmission.fromJson(json)).toList();
    } catch (e) {
      print('Failed to get all submissions: $e');
      return [];
    }
  }

  /// 根据类别获取内容分享
  Future<List<ContentSubmission>> getSubmissionsByCategory(SubmissionCategory category) async {
    try {
      final allSubmissions = await getAllSubmissions();
      return allSubmissions.where((submission) => submission.category == category).toList();
    } catch (e) {
      print('Failed to get submissions by category: $e');
      return [];
    }
  }

  /// 根据用户ID获取内容分享
  Future<List<ContentSubmission>> getSubmissionsByAuthor(String authorId) async {
    try {
      final allSubmissions = await getAllSubmissions();
      return allSubmissions.where((submission) => submission.authorId == authorId).toList();
    } catch (e) {
      print('Failed to get submissions by author: $e');
      return [];
    }
  }

  /// 根据ID获取单个内容分享
  Future<ContentSubmission?> getSubmissionById(String submissionId) async {
    try {
      final allSubmissions = await getAllSubmissions();
      return allSubmissions.firstWhere(
        (submission) => submission.submissionId == submissionId,
        orElse: () => throw Exception('Submission not found'),
      );
    } catch (e) {
      print('Failed to get submission by ID: $e');
      return null;
    }
  }

  /// 发布新的内容分享
  Future<bool> publishSubmission(ContentSubmission submission) async {
    try {
      final allSubmissions = await getAllSubmissions();
      
      // 检查是否已存在相同ID的分享
      final existingIndex = allSubmissions.indexWhere(
        (s) => s.submissionId == submission.submissionId,
      );
      
      if (existingIndex != -1) {
        // 更新现有分享
        allSubmissions[existingIndex] = submission;
      } else {
        // 添加新分享
        allSubmissions.add(submission);
      }
      
      // 按发布时间倒序排列
      allSubmissions.sort((a, b) => b.publishedAt.compareTo(a.publishedAt));
      
      return await _saveAllSubmissions(allSubmissions);
    } catch (e) {
      print('Failed to publish submission: $e');
      return false;
    }
  }

  /// 更新内容分享
  Future<bool> updateSubmission(ContentSubmission submission) async {
    try {
      final allSubmissions = await getAllSubmissions();
      final index = allSubmissions.indexWhere(
        (s) => s.submissionId == submission.submissionId,
      );
      
      if (index == -1) {
        return false;
      }
      
      allSubmissions[index] = submission;
      return await _saveAllSubmissions(allSubmissions);
    } catch (e) {
      print('Failed to update submission: $e');
      return false;
    }
  }

  /// 删除内容分享
  Future<bool> removeSubmission(String submissionId) async {
    try {
      final allSubmissions = await getAllSubmissions();
      final initialLength = allSubmissions.length;
      
      allSubmissions.removeWhere((s) => s.submissionId == submissionId);
      
      if (allSubmissions.length == initialLength) {
        return false; // 没有找到要删除的分享
      }
      
      return await _saveAllSubmissions(allSubmissions);
    } catch (e) {
      print('Failed to remove submission: $e');
      return false;
    }
  }

  /// 切换点赞状态
  Future<bool> toggleAppreciation(String submissionId, User currentUser) async {
    try {
      final submission = await getSubmissionById(submissionId);
      if (submission == null) {
        return false;
      }
      
      final List<UserInteraction> appreciations = List.from(submission.appreciations);
      final bool isAlreadyAppreciated = submission.isAppreciatedByUser(currentUser.id);
      
      if (isAlreadyAppreciated) {
        // 取消点赞
        appreciations.removeWhere((interaction) => interaction.userId == currentUser.id);
      } else {
        // 添加点赞
        final newInteraction = UserInteraction(
          interactionId: 'like_${DateTime.now().millisecondsSinceEpoch}',
          userId: currentUser.id,
          userName: currentUser.name,
          userAvatar: currentUser.avatar,
          interactedAt: DateTime.now(),
        );
        appreciations.add(newInteraction);
      }
      
      final updatedSubmission = submission.copyWithAppreciation(
        appreciations: appreciations,
        appreciationCount: appreciations.length,
      );
      
      return await updateSubmission(updatedSubmission);
    } catch (e) {
      print('Failed to toggle appreciation: $e');
      return false;
    }
  }

  /// 保存所有内容分享到本地存储
  Future<bool> _saveAllSubmissions(List<ContentSubmission> submissions) async {
    try {
      final List<Map<String, dynamic>> submissionsJson = 
          submissions.map((s) => s.toJson()).toList();
      final String jsonString = jsonEncode(submissionsJson);
      
      await _localStore.setTextValue(_submissionsKey, jsonString);
      return true;
    } catch (e) {
      print('Failed to save submissions: $e');
      return false;
    }
  }

  /// 获取所有挑战任务
  Future<List<ChallengeTask>> getAllChallengeTasks() async {
    try {
      final String tasksJson = _localStore.getTextValue(
        _challengeTasksKey,
        defaultValue: '[]',
      );
      
      final List<dynamic> jsonList = jsonDecode(tasksJson);
      return jsonList.map((json) => ChallengeTask.fromJson(json)).toList();
    } catch (e) {
      print('Failed to get challenge tasks: $e');
      return _getDefaultChallengeTasks();
    }
  }

  /// 根据ID获取挑战任务
  Future<ChallengeTask?> getChallengeTaskById(String taskId) async {
    try {
      final allTasks = await getAllChallengeTasks();
      return allTasks.firstWhere(
        (task) => task.taskId == taskId,
        orElse: () => throw Exception('Task not found'),
      );
    } catch (e) {
      print('Failed to get challenge task by ID: $e');
      return null;
    }
  }

  /// 初始化默认挑战任务
  Future<void> initializeChallengeTasks() async {
    try {
      final existingTasks = await getAllChallengeTasks();
      if (existingTasks.isEmpty) {
        final defaultTasks = _getDefaultChallengeTasks();
        final List<Map<String, dynamic>> tasksJson = 
            defaultTasks.map((task) => task.toJson()).toList();
        final String jsonString = jsonEncode(tasksJson);
        
        await _localStore.setTextValue(_challengeTasksKey, jsonString);
      }
    } catch (e) {
      print('Failed to initialize challenge tasks: $e');
    }
  }

  /// 获取默认挑战任务列表
  List<ChallengeTask> _getDefaultChallengeTasks() {
    return [
      const ChallengeTask(
        taskId: 'brush_teeth',
        taskTitle: 'Brush Teeth Every Day',
        taskTag: '#Brush teeth',
        taskDescription: 'Maintain oral hygiene by brushing teeth daily',
      ),
      const ChallengeTask(
        taskId: 'dental_floss',
        taskTitle: 'Daily Dental Floss',
        taskTag: '#Dental floss',
        taskDescription: 'Use dental floss for better oral care',
      ),
      const ChallengeTask(
        taskId: 'daily_food',
        taskTitle: 'Daily Food Check-In',
        taskTag: '#Daily food',
        taskDescription: 'Track and share your daily food intake',
      ),
    ];
  }

  /// 清理数据
  Future<void> clearAllData() async {
    try {
      await _localStore.removeValue(_submissionsKey);
      await _localStore.removeValue(_challengeTasksKey);
    } catch (e) {
      print('Failed to clear data: $e');
    }
  }
}
